/*
 * @Author: Eli.Chen
 * @Date: 2025-05-07 10:04:52
 * @LastEditors: Eli.Chen
 * @LastEditTime: 2025-05-09 17:01:08
 * @Description:
 */
const fs = require('fs');
const path = require('path');
const prettier = require('prettier');

const pagesPath = path.join(process.cwd(), 'src/views');
const outputPath = path.join(process.cwd(), 'src/router/index.js');

const generateRoutes = async () => {
    const walkDir = (dir) => {
        const results = [];
        const list = fs.readdirSync(dir);

        const excludedDirs = ['admin', 'user', 'auth', 'adminController', 'suggestion', 'articleDetail'];

        list.forEach((file) => {
            const filePath = path.join(dir, file);
            const stat = fs.statSync(filePath);

            if (stat && stat.isDirectory()) {
                // 添加目录过滤条件
                if (!excludedDirs.includes(file)) {
                    results.push(...walkDir(filePath));
                }
            } else if (/\.(jsx|tsx)$/.test(file)) {
                results.push(path.relative(pagesPath, filePath));
            }
        });

        return results;
    };

    const componentMap = {};
    const components = walkDir(pagesPath)
        .map((filePath) => {
            const componentName = path
                .basename(filePath)
                .replace(/\.(jsx|tsx)$/, '')
                .replace(/^\w/, (c) => c.toUpperCase());

            if (!componentMap[componentName]) {
                componentMap[componentName] = true;
                // 路径改为 @/views/ 别名格式，替换 \ 为 / 避免路径错误
                return `import ${componentName} from '@/views/${filePath.replace(/\\/g, '/')}';`;
            }
            return '';
        })
        .filter(Boolean);

    const routes = walkDir(pagesPath).map((filePath) => {
        const dirName = path.dirname(filePath);
        const baseName = path.basename(filePath, path.extname(filePath));
        const lastDir = path.basename(dirName);

        const routePath =
            lastDir.toLowerCase() === baseName.toLowerCase()
                ? dirName.toLowerCase().replace(/\\/g, '/')
                : path
                      .join(
                          dirName.toLowerCase(),
                          baseName.replace(/^\w/, (c) => c.toLowerCase())
                      )
                      .replace(/\\/g, '/');

        const componentName = baseName
            .replace(/^\w/, (c) => c.toUpperCase())
            .replace(/(?:^|-|_)(\w)/g, (_, c) => c.toUpperCase());

        // 缩进从 2 空格改为 4 空格，匹配 Prettier 配置
        return `    {
        path: '/${routePath}',
        element: <${componentName} />
    },`;
    });

    const template = `import { createBrowserRouter } from 'react-router-dom';
import React from 'react';
import { Outlet } from 'react-router-dom';
import MainLayout from '@/layout/mainLayout/MainLayout';
import AdminController from '@/views/adminController/AdminController';
import UserHome from '@/views/client/user/UserHome';
import EditProfile from '@/views/client/user/EditProfile';
import WorkCenter from '@/views/client/user/WorkCenter';
import UserSetting from '@/views/client/user/UserSetting';
import CultPopMan from '@/views/admin/cultPopMan/CultPopMan';
import ArticleDetail from '@/views/client/articleDetail/ArticleDetail';
import HomeMan from '@/views/admin/homeMan/HomeMan';
import UserMan from '@/views/admin/userMan/UserMan';
import FoodMan from '@/views/admin/suggestMan/FoodMan';
import TouristMan from '@/views/admin/suggestMan/TouristMan';
import TradCraftMan from '@/views/admin/suggestMan/TradCraftMan';
import PublishMan from '@/views/admin/suggestMan/PublishMan';
import AdminDashboard from '@/views/admin/adminDashboard/AdminDashboard';
import UserWorkReview from '@/views/admin/userWorkReview/UserWorkReview';
import Login from '@/views/auth/login/Login.jsx';
import Register from '@/views/auth/register/Register.jsx';
import ForgetPassword from '@/views/auth/forgetPassword/ForgetPassword.jsx';
import AdminLogin from '@/views/auth/admin/adminLogin/AdminLogin.jsx';
import Suggestion from '@/views/client/suggestion/Suggestion.jsx';
import AuthWrapper from '@/components/common/AuthWrapper';
${components.join('\n')}

const routes = createBrowserRouter([
    {
        path: '/',
        element: <MainLayout />,
        children: [
            { 
                index: true, 
                element: (
                    <>
                        <Home /> 
                        <Outlet />
                    </>
                )
            },
            { 
                path: 'cultPop',
                children: [
                    {
                        index: true,
                        element: <CultPop />,
                    },
                    {
                        path: ':articleId',
                        element: <ArticleDetail />
                    }
                ]
            },
            { path: 'suggestion', element: <Suggestion /> },
            { path: 'community', element: <AuthWrapper validate={false}><Community /></AuthWrapper> }
        ]
    },
    {
        path: '/auth',
        children: [
            {
                path: 'login',
                element: <Login />
            },
            {
                path: 'register',
                element: <Register />
            },
            {
                path: 'forgetpassword',
                element: <ForgetPassword />
            },
            {
                path: 'admin/login',
                element: <AdminLogin />
            }
        ]
    },
    {
        path: '/adminController',
        element: <AdminController />,
        children: [
            {
                index: true,
                element: <AdminDashboard />
            },
            { 
                path: 'cultPopMan',
                element: <CultPopMan />
            },
            {
                path: 'homeMan',
                element: <HomeMan />
            },
            {
                path: 'userMan',
                element: <UserMan />
            },
            {
                path: 'userWorkReview',
                element: <UserWorkReview />
            },
            {
                path: 'recommend',
                children: [
                    {
                        index: true,
                        element: <PublishMan />
                    },
                    {
                        path: 'foodMan',
                        element: <FoodMan />
                    },
                    {
                        path: 'touristMan',
                        element: <TouristMan />
                    },
                    {
                        path: 'tradCraftMan',
                        element: <TradCraftMan />
                    }
                ]
            }
        ]
    },
    {
        path: '/user',
        element: <UserHome />,
        children: [
            {
                index: true,
                element: <WorkCenter />
            },
            {
                path: 'editProfile',
                element: <EditProfile />
            },
            {
                path: 'userSetting',
                element: <UserSetting />
            }
        ]
    },
${routes.join('\n')}
]);

export default routes;
`;

    // 补充完整 Prettier 配置，和项目 .prettierrc 保持一致
    const formatted = await prettier.format(template, {
        parser: 'babel',
        singleQuote: true,
        tabWidth: 4,
        useTabs: false,
        endOfLine: 'lf',
        semi: true,
        printWidth: 120,
        trailingComma: 'es5',
        arrowParens: 'always',
        jsxSingleQuote: false,
        bracketSpacing: true,
        bracketSameLine: false,
    });

    fs.writeFileSync(outputPath, formatted);
};

generateRoutes().catch((err) => {
    console.error('路由生成失败:', err);
    process.exit(1);
});
